package com.xiaoyu.lanling.activity.base;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.xiaoyu.lanling.R;

import in.srain.cube.util.LocalDisplay;

public abstract class AppCompatToolbarActivity extends BaseAppCompatActivity {

    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static final int DEFAULT_HOME_AS_UP_INDICATOR_RES = R.drawable.icon_toolbar_action_back;
    private long mLastClickTime = 0;

    protected Toolbar mToolBar;
    private float mSlideBackDistance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    protected void initToolbar() {
        initToolbar(DEFAULT_HOME_AS_UP_INDICATOR_RES);
    }

    protected void initToolbar(int homeAsUpIndicatorRes) {
        mToolBar = this.findViewById(R.id.toolbar);
        if (mToolBar != null) {
            setSupportActionBar(mToolBar);
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeAsUpIndicator(homeAsUpIndicatorRes);
            }
        }
        setTitle("");
    }

    protected void setToolbarElevation(int elevation) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setElevation(LocalDisplay.dp2px(elevation));
        }
    }

    protected void setToolbarNavigationIcon(int resId) {
        if (mToolBar != null) {
            mToolBar.setNavigationIcon(resId);
        }
    }

    protected void setTranslucent() {
        QMUIStatusBarHelper.translucent(this);
    }

    protected void setLightStatusBar() {
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    protected void setDarkStatusBar() {
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                if (isInvalidClick()) {
                    return super.onOptionsItemSelected(item);
                } else {
                    return onDebounceOptionsItemSelected(item);
                }
        }
    }

    private boolean isInvalidClick() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - mLastClickTime > MIN_CLICK_DELAY_TIME) {
            mLastClickTime = currentTime;
            return false;
        }
        return true;
    }

    public boolean onDebounceOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}
